package goods

import (
	"ferry/global/orm"
	"ferry/models/goods"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"net/http"
	"strconv"
	"time"
)

// GetGoodsList 获取商品列表
func GetGoodsList(c *gin.Context) {
	var (
		pageIndex = 1
		pageSize  = 20
		name      = c.DefaultQuery("name", "")
		status    = c.DefaultQuery("status", "")
		goodsList []goods.Goods
		total     int64
		err       error
	)

	// 解析分页参数
	if pageIndexStr := c.DefaultQuery("pageIndex", "1"); pageIndexStr != "" {
		if pi, err := strconv.Atoi(pageIndexStr); err == nil {
			pageIndex = pi
		}
	}
	if pageSizeStr := c.DefaultQuery("pageSize", "20"); pageSizeStr != "" {
		if ps, err := strconv.Atoi(pageSizeStr); err == nil {
			pageSize = ps
		}
	}

	// 构建查询
	db := orm.Eloquent
	if name != "" {
		db = db.Where("name LIKE ?", "%"+name+"%")
	}
	if status != "" {
		db = db.Where("status = ?", status)
	}

	// 查询总数
	db.Model(&goods.Goods{}).Count(&total)

	// 分页查询
	offset := (pageIndex - 1) * pageSize
	err = db.Offset(offset).Limit(pageSize).Find(&goodsList).Error
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"list":      goodsList,
			"total":     total,
			"pageIndex": pageIndex,
			"pageSize":  pageSize,
		},
	})
}

// GetGoods 获取商品详情
func GetGoods(c *gin.Context) {
	var (
		goodsInfo goods.Goods
		id        = c.Param("id")
		err       error
	)

	err = orm.Eloquent.Where("id = ?", id).First(&goodsInfo).Error
	if err != nil {
		if gorm.IsRecordNotFoundError(err) {
			c.JSON(http.StatusNotFound, gin.H{
				"code": 404,
				"msg":  "商品不存在",
			})
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{
				"code": 500,
				"msg":  "查询失败",
			})
		}
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": goodsInfo,
	})
}

// CreateGoods 创建商品
func CreateGoods(c *gin.Context) {
	var (
		goodsInfo goods.Goods
		err       error
	)

	err = c.ShouldBindJSON(&goodsInfo)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}

	// 验证必填字段
	if goodsInfo.Name == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "商品名称不能为空",
		})
		return
	}

	// 设置创建时间
	now := time.Now().Format("2006-01-02 15:04:05")
	goodsInfo.CreateTime = now
	goodsInfo.UpdateTime = now

	err = orm.Eloquent.Create(&goodsInfo).Error
	if err != nil {
		fmt.Println("商品新增报错", err)
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "创建失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "创建成功",
		"data": goodsInfo,
	})
}

// UpdateGoods 更新商品
func UpdateGoods(c *gin.Context) {
	var (
		goodsInfo goods.Goods
		id        = c.Param("id")
		err       error
	)

	// 检查商品是否存在
	err = orm.Eloquent.Where("id = ?", id).First(&goodsInfo).Error
	if err != nil {
		if gorm.IsRecordNotFoundError(err) {
			c.JSON(http.StatusNotFound, gin.H{
				"code": 404,
				"msg":  "商品不存在",
			})
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{
				"code": 500,
				"msg":  "查询失败",
			})
		}
		return
	}

	// 绑定更新数据
	var updateData goods.Goods
	err = c.ShouldBindJSON(&updateData)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "参数错误",
		})
		return
	}

	// 验证必填字段
	if updateData.Name == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "商品名称不能为空",
		})
		return
	}

	// 设置更新时间
	now := time.Now().Format("2006-01-02 15:04:05")
	updateData.UpdateTime = now

	// 添加调试日志
	fmt.Printf("更新前商品信息: ID=%d, Status=%d\n", goodsInfo.Id, goodsInfo.Status)
	fmt.Printf("更新数据: Name=%s, Status=%d, ID=%d\n", updateData.Name, updateData.Status, goodsInfo.Id)
	fmt.Printf("前端传递的完整JSON数据: %+v\n", updateData)

	// 启用SQL日志
	db := orm.Eloquent.Debug()

	// 更新商品 - 使用Map方式确保零值字段也能更新
	updateMap := map[string]interface{}{
		"name":        updateData.Name,
		"description": updateData.Description,
		"image":       updateData.Image,
		"points":      updateData.Points,
		"stock":       updateData.Stock,
		"status":      updateData.Status,
		"update_time": updateData.UpdateTime,
	}
	result := db.Model(&goods.Goods{}).Where("id = ?", goodsInfo.Id).Updates(updateMap)
	if result.Error != nil {
		fmt.Printf("更新失败: %v\n", result.Error)
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "更新失败",
		})
		return
	}
	fmt.Printf("更新成功，受影响行数: %d\n", result.RowsAffected)

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "更新成功",
		"data": goodsInfo,
	})
}

// DeleteGoods 删除商品
func DeleteGoods(c *gin.Context) {
	var (
		goodsInfo goods.Goods
		id        = c.Param("id")
		err       error
	)

	// 检查商品是否存在
	err = orm.Eloquent.Where("id = ?", id).First(&goodsInfo).Error
	if err != nil {
		if gorm.IsRecordNotFoundError(err) {
			c.JSON(http.StatusNotFound, gin.H{
				"code": 404,
				"msg":  "商品不存在",
			})
		} else {
			c.JSON(http.StatusInternalServerError, gin.H{
				"code": 500,
				"msg":  "查询失败",
			})
		}
		return
	}

	// 软删除商品
	err = orm.Eloquent.Delete(&goodsInfo).Error
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}
